package com.gzhryc.net_marketing.supplier.pay.services;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.IDTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.net_marketing.api.CloudGoodsOrderAPIService;
import com.gzhryc.net_marketing.api.CloudPayAccountAPIService;
import com.gzhryc.net_marketing.api.protocol.account.CloudPayAccountSearchOrderInfoResponse;
import com.gzhryc.net_marketing.api.protocol.account.CloudPayAccountSettlementRequest;
import com.gzhryc.net_marketing.api.protocol.account.CloudPayAccountSettlementResponse;
import com.gzhryc.net_marketing.api.protocol.order.ConfirmGoodsOrderRequest;
import com.gzhryc.net_marketing.api.protocol.order.UpdateGoodsOrderStateRequest;
import com.gzhryc.net_marketing.core.enums.*;
import com.gzhryc.net_marketing.supplier.Supplier;
import com.gzhryc.net_marketing.supplier.config.dao.db.SupplierLogisticsCompany;
import com.gzhryc.net_marketing.supplier.config.dao.db.SupplierLogisticsCostConfig;
import com.gzhryc.net_marketing.supplier.config.services.SupplierLogisticsCompanyService;
import com.gzhryc.net_marketing.supplier.config.services.SupplierLogisticsCostConfigService;
import com.gzhryc.net_marketing.supplier.erp.dao.db.SupplierGoods;
import com.gzhryc.net_marketing.supplier.erp.dao.db.SupplierGoodsSpace;
import com.gzhryc.net_marketing.supplier.pay.dao.SupplierBusinessOrderDao;
import com.gzhryc.net_marketing.supplier.pay.dao.db.SupplierBusinessOrder;
import com.gzhryc.net_marketing.supplier.pay.services.dto.PayConfig;
import com.gzhryc.net_marketing.supplier.pay.services.dto.ReceiveAddress;
import com.gzhryc.net_marketing.supplier.pay.services.dto.SupplierBusinessOrderSearch;
import com.gzhryc.shared_device.base.enums.EPayState;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.net_marketing.api.protocol.account.CloudPayNotifyRequest;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class SupplierBusinessOrderService {

	static Logger log = Logger.getLogger(SupplierBusinessOrderService.class);

	public static SupplierBusinessOrderService self() {
		return MultiDBTools.getService(SupplierBusinessOrderService.class, true);
	}

	public static SupplierBusinessOrderService self(String jdbcKey) {
		return MultiDBTools.getService(jdbcKey, SupplierBusinessOrderService.class, true);
	}

	SupplierBusinessOrderDao dao;

	public SupplierBusinessOrderService(String jdbcKey) {
		dao = new SupplierBusinessOrderDao(jdbcKey);
	}

	public List<SupplierBusinessOrder> findBySearch(SupplierBusinessOrderSearch search, Integer pageNo, Integer pageLimit) {
		Conditions condition = dao.buildConditions(search);
		condition.and().le("deliverGoodsDate",search.getEndDeliverGoodsDate());
		condition.and().le("receiveGoodsDate",search.getEndReceiveGoodsDate());
		condition.desc("createDate");
		try {
			return dao.findByCondition(condition, pageNo, pageLimit);
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}
	
	public Long countBySearch(SupplierBusinessOrderSearch search) {
		Conditions condition = dao.buildConditions(search);
		condition.and().le("deliverGoodsDate",search.getEndDeliverGoodsDate());
		condition.and().le("receiveGoodsDate",search.getEndReceiveGoodsDate());
		try {
			return dao.count(condition);
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
		return 0L;
	}

	public SupplierBusinessOrder getByTradeNo(String tradeNo){
		if(StringTools.isNotBlank(tradeNo)){
			try {
				return dao.getById(tradeNo);
			} catch (SQLException e) {
				log.error(e.getMessage(),e);
			}
		}
		return null;
	}
	public SupplierBusinessOrder getByProjectTradeNo(String projectTradeNo){
		if(StringTools.isNotBlank(projectTradeNo)){
			Conditions conditions = new Conditions(SupplierBusinessOrder.class);
			conditions.and().is("projectTradeNo",projectTradeNo);
			try {
				return dao.get(conditions);
			} catch (SQLException e) {
				log.error(e.getMessage(),e);
			}
		}
		return null;
	}


	public SupplierBusinessOrder buildBusinessOrder(Supplier supplier, SupplierGoods goods, SupplierGoodsSpace goodsSpace, ReceiveAddress receiveAddress, PayConfig payConfig) throws LogicException {
		SupplierBusinessOrder businessOrder = getByProjectTradeNo(payConfig.getProjectTradeNo());
		if (businessOrder != null) {
			//检查是否同一个商品
			if (businessOrder.getGoodsCode().equals(goods.getCode()) && businessOrder.getGoodsCount().equals(payConfig.getGoodsCount())) {
				if ((goodsSpace == null && businessOrder.getGoodsSpaceId() == null) || (goodsSpace != null && goodsSpace.getId().equals(businessOrder.getGoodsSpaceId()))) {
					if (businessOrder.getGoodsMoney().equals(goods.getPayMoney())) {
						if (businessOrder.getReceivePhone().equals(receiveAddress.getPhone()) && businessOrder.getReceiveProvince().equals(receiveAddress.getProvince())
								&& businessOrder.getReceiveAddress().equals(receiveAddress.getAddress())) {
							return businessOrder;
						} else {
							throw new LogicException("存在相同的商城项目订单号");
						}
					} else {
						throw new LogicException("存在相同的商城项目订单号");
					}
				} else {
					throw new LogicException("存在相同的商城项目订单号");
				}
			} else {
				throw new LogicException("存在相同的商城项目订单号");
			}
		}

		businessOrder = new SupplierBusinessOrder();
		businessOrder.setProjectId(payConfig.getProjectId());
		businessOrder.setProjectName(payConfig.getProjectName());
		businessOrder.setProjectTradeNo(payConfig.getProjectTradeNo());
		businessOrder.setGoodsId(goods.getId());
		businessOrder.setGoodsCode(goods.getCode());
		businessOrder.setGoodsClassify(goods.getClassify());
		businessOrder.setTypeCodes(goods.getTypeCodes());
		businessOrder.setTypeNames(goods.getTypeNames());
		if (goodsSpace != null) {
			businessOrder.setGoodsSpaceId(goodsSpace.getId());
			businessOrder.setGoodsSpaceName(goodsSpace.getName());
		}
		businessOrder.setGoodsName(goods.getName());
		businessOrder.setGoodsImg(goods.getThumbnailImg());
		businessOrder.setGoodsCount(payConfig.getGoodsCount());
		businessOrder.setGoodsMoney(goods.getPayMoney());
		businessOrder.setNote(payConfig.getNote());
		businessOrder.setReceiveName(receiveAddress.getName());
		businessOrder.setReceivePhone(receiveAddress.getPhone());
		businessOrder.setReceiveProvince(receiveAddress.getProvince());
		businessOrder.setReceiveAddress(receiveAddress.getAddress());

		//计算金额
		Integer money = businessOrder.getGoodsMoney() * payConfig.getGoodsCount();
		Integer logisticsMoney = 0;

		if (EGoodsClassify.Entity.index().equals(goods.getClassify())) {
			SupplierLogisticsCostConfig logisticsCostConfig = null;
			try {
				//获取物流费用
				logisticsCostConfig = SupplierLogisticsCostConfigService.self().getUsableConfig(payConfig.getLogisticsCompanyId()
						, receiveAddress.getProvince());
				if (logisticsCostConfig == null) {
					throw new LogicException("未找到物流价格配置");
				} else if (logisticsCostConfig.getFreeMinMoney() == null
						|| (logisticsCostConfig.getFreeMinMoney() > 0 && money > logisticsCostConfig.getFreeMinMoney())) {
					log.info("客单价触发免邮费，客单价：{{0}}，阀值：{{1}}", money, logisticsCostConfig.getFreeMinMoney());
				} else {
					logisticsMoney = logisticsCostConfig.getMoney();
					money = money + logisticsMoney;
				}
			} catch (LogicException e) {
				if (payConfig.getLogisticsCompanyId() != null) {
					throw e;
				}
			}
			//物流信息
			if (logisticsCostConfig != null) {
				businessOrder.setLogisticsCompanyId(logisticsCostConfig.getCompanyId());
				businessOrder.setLogisticsCompany(logisticsCostConfig.getCompanyName());
			} else if (payConfig.getLogisticsCompanyId() != null) {
				SupplierLogisticsCompany company = SupplierLogisticsCompanyService.self().getById(payConfig.getLogisticsCompanyId());
				if (company != null) {
					businessOrder.setLogisticsCompanyId(company.getId());
					businessOrder.setLogisticsCompany(company.getName());
				} else {
					log.error("{{0}}供应链应用用户指定的物流公司不存在，物流公司ID：{{1}}", supplier.getId(), payConfig.getLogisticsCompanyId());
				}
			}
		}

		businessOrder.setTradeNo(createTradeNo(supplier.getId()));
		businessOrder.setMoney(money);
		businessOrder.setLogisticsMoney(logisticsMoney);
		businessOrder.setPayMoney(money);
		businessOrder.setState(GoodsOrderEnum.State.Wait.index());
		businessOrder.setCreateDate(new Date());

		try {
			if (dao.insert(businessOrder) > 0) {
				return businessOrder;
			}
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	public boolean payResult(CloudPayNotifyRequest notify){
		if(EPayState.Success.index().equals(notify.getBody().getPayResult())){
			SupplierBusinessOrder businessOrder = this.getByTradeNo(notify.getBody().getBusinessTradeNo());
			if(businessOrder != null){
				if(GoodsOrderEnum.State.Wait.index().equals(businessOrder.getState())) {
					Conditions condition = new Conditions(SupplierBusinessOrder.class);
					condition.and().is("tradeNo", businessOrder.getTradeNo());
					condition.and().is("state", GoodsOrderEnum.State.Wait.index());

					SupplierBusinessOrder updateEntity = new SupplierBusinessOrder();
					updateEntity.setPayTradeNo(notify.getBody().getTradeNo());
					updateEntity.setPayDate(new Date());
					updateEntity.setState(GoodsOrderEnum.State.WaitDeliver.index());

					try {
						if(dao.updateNotNull(updateEntity, condition) > 0){
							return true;
						}
					} catch (SQLException e) {
						log.error(e.getMessage(),e);
					}
				}
			}else{
				log.error("支付结果处理时未找到业务订单，支付通知信息：{{0:json}}",notify);
			}
		}
		return false;
	}

	/**
	 * 查询订单信息
	 * 1.目前只支持云支付的支付结果查询
	 * @param supplier
	 * @param businessOrder
	 * @return
	 * @throws LogicException
	 */
	public boolean searchOrderInfo(Supplier supplier,SupplierBusinessOrder businessOrder) throws LogicException{
		//调用云支付接口查询
		CloudPayAccountSearchOrderInfoResponse apiResp = CloudPayAccountAPIService.self().searchOrder(supplier.getAccountId()
				,supplier.getPayToken(),businessOrder.getTradeNo());
		if(apiResp == null){
			new LogicException("云支付无返回");
		}
		if(!DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())){
			new LogicException(apiResp.getMsg());
		}
		if(EPayState.Success.index().equals(apiResp.getBody().getPayResult())){
			CloudPayNotifyRequest notify = new CloudPayNotifyRequest();
			notify.setBody(ClassTools.copy(notify.getBody(),apiResp.getBody()));
			return this.payResult(notify);
		}else {
			new LogicException("云支付失败，请等待对方重新支付");
		}
		return false;
	}

	public boolean updateReceiveAddress(SupplierBusinessOrder businessOrder) throws LogicException {
		if(GoodsOrderEnum.SupplyState.WaitConfirm.index().equals(businessOrder.getSupplyState())){
			Conditions conditions = new Conditions(SupplierBusinessOrder.class);
			conditions.and().is("tradeNo",businessOrder.getTradeNo());
			conditions.and().is("state",GoodsOrderEnum.State.WaitDeliver.index());
			conditions.and().is("supplyState",GoodsOrderEnum.SupplyState.WaitConfirm.index());

			SupplierBusinessOrder updateEntity = new SupplierBusinessOrder();
			updateEntity.setReceiveName(businessOrder.getReceiveName());
			updateEntity.setReceivePhone(businessOrder.getReceivePhone());
			updateEntity.setReceiveProvince(businessOrder.getReceiveProvince());
			updateEntity.setReceiveAddress(businessOrder.getReceiveAddress());

			try {
				return dao.updateNotNull(updateEntity,conditions) > 0;
			} catch (SQLException e) {
				log.error(e.getMessage(),e);
			}
		}else{
			throw new LogicException("订单已确认无法修改收货地址");
		}
		return false;
	}

	/**
	 * 确定订单可以发货
	 * @param businessOrder
	 * @param supplyState
	 * @return
	 * @throws LogicException
	 */
	public boolean confirmOrder(SupplierBusinessOrder businessOrder,Integer supplyState,OperateInfo operateInfo) throws LogicException{
		SupplierBusinessOrder updateEntity = new SupplierBusinessOrder();
		updateEntity.setTradeNo(businessOrder.getTradeNo());
		updateEntity.setSupplyState(supplyState);

		boolean flag = false;
		try {
			if(dao.updateNotNull(updateEntity) > 0){
				SupplierBusinessOrderLogService.self().addSuccess(businessOrder.getTradeNo(),"确认订单有库存并物流可达", operateInfo.getProgramType()
						, operateInfo.getOperatorType(),operateInfo.getOperator());
				flag = true;
			}
		} catch (SQLException e) {
			log.error(e.getMessage(),e);
		}
		if(flag){
			ConfirmGoodsOrderRequest apiReq = new ConfirmGoodsOrderRequest();
			apiReq.getBody().setTradeNo(businessOrder.getTradeNo());
			apiReq.getBody().setConfirmState(true);

			DefaultAPIResponse apiResp = CloudGoodsOrderAPIService.self().confirmGoodsOrder(apiReq);
			if(apiResp == null){
				log.error("{{0}}订单通知云平台确认失败，无响应",businessOrder.getTradeNo());
			}else if(!DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())){
				log.error("{{0}}订单通知云平台确认失败，响应：{{1}}",businessOrder.getTradeNo(),apiResp.getMsg());
			}
			return true;
		}
		return false;
	}

	/**
	 * 物流发货处理
	 * @return
	 */
	public boolean logisticsDeliveryGoods(SupplierBusinessOrder businessOrder,String logisticsCompanyId,String logisticsCompanyTradeNo,Date deliverGoodsDate,OperateInfo operateInfo) throws LogicException {
		if(businessOrder != null && logisticsCompanyId != null && StringTools.isNotBlank(logisticsCompanyTradeNo)
			&& deliverGoodsDate != null){
			SupplierLogisticsCompany logisticsCompany = SupplierLogisticsCompanyService.self().getById(logisticsCompanyId);
			if(logisticsCompany == null){
				throw new LogicException("未找到物流公司信息");
			}

			if(!GoodsOrderEnum.State.WaitDeliver.index().equals(businessOrder.getState())) {
				throw  new LogicException("订单未支付或已发货");
			}

			Conditions conditions = new Conditions(SupplierBusinessOrder.class);
			conditions.and().is("tradeNo",businessOrder.getTradeNo());
			conditions.and().is("goodsClassify", EGoodsClassify.Entity.index());
			conditions.and().is("state", GoodsOrderEnum.State.WaitDeliver.index());

			SupplierBusinessOrder updateEntity = new SupplierBusinessOrder();
			updateEntity.setLogisticsCompanyId(logisticsCompanyId);
			updateEntity.setLogisticsCompany(logisticsCompany.getName());
			updateEntity.setLogisticsTradeNo(logisticsCompanyTradeNo);
			updateEntity.setDeliverGoodsDate(deliverGoodsDate);
			updateEntity.setState(GoodsOrderEnum.State.WaitReceive.index());

			boolean flag = false;
			try {
				if(dao.updateNotNull(updateEntity,conditions) > 0){
					SupplierBusinessOrderLogService.self().addSuccess(businessOrder.getTradeNo(),"实体商品发货处理", operateInfo.getProgramType()
							, operateInfo.getOperatorType(),operateInfo.getOperator());
					flag = true;
				}
			} catch (SQLException e) {
				log.error(e.getMessage(),e);
			}

			if(flag){
				//网商平台通知，已发货
				UpdateGoodsOrderStateRequest apiReq = new UpdateGoodsOrderStateRequest();
				apiReq.getBody().setTradeNo(businessOrder.getTradeNo());
				apiReq.getBody().setState(GoodsOrderEnum.State.WaitReceive.index());
				apiReq.getBody().setLogisticsCompanyId(logisticsCompanyId);
				apiReq.getBody().setLogisticsCompany(logisticsCompany.getName());
				apiReq.getBody().setLogisticsTradeNo(logisticsCompanyTradeNo);
				apiReq.getBody().setDeliverGoodsDate(deliverGoodsDate);

				DefaultAPIResponse apiResp = CloudGoodsOrderAPIService.self().updateGoodsOrderState(apiReq);
				if(apiResp == null){
					log.error("{{0}}订单通知云平台已发货失败，无响应",businessOrder.getTradeNo());
				}else if(!DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())){
					log.error("{{0}}订单通知云平台已发货失败，响应：{{1}}",businessOrder.getTradeNo(),apiResp.getMsg());
				}
				return true;
			}
		}
		return false;
	}

	/**
	 * 发货处理
	 * @param businessOrder
	 * @param deliverGoodsNote
	 * @param deliverGoodsDate
	 * @return
	 * @throws LogicException
	 */
	public boolean deliveryGoods(SupplierBusinessOrder businessOrder, String deliverGoodsNote, Date deliverGoodsDate, OperateInfo operateInfo) throws LogicException {
		if(businessOrder != null && StringTools.isNotBlank(deliverGoodsNote) && deliverGoodsDate != null){
			if(!GoodsOrderEnum.State.WaitDeliver.index().equals(businessOrder.getState())) {
				throw  new LogicException("订单未支付或已发货");
			}

			Conditions conditions = new Conditions(SupplierBusinessOrder.class);
			conditions.and().is("tradeNo",businessOrder.getTradeNo());
			conditions.and().is("goodsClassify", EGoodsClassify.Fictitious.index());
			conditions.and().is("state", GoodsOrderEnum.State.WaitDeliver.index());

			SupplierBusinessOrder updateEntity = new SupplierBusinessOrder();
			updateEntity.setDeliverGoodsNote(deliverGoodsNote);
			updateEntity.setDeliverGoodsDate(deliverGoodsDate == null?new Date():deliverGoodsDate);
			updateEntity.setState(GoodsOrderEnum.State.WaitReceive.index());

			boolean flag = false;
			try {
				if(dao.updateNotNull(updateEntity,conditions) > 0){
					SupplierBusinessOrderLogService.self().addSuccess(businessOrder.getTradeNo(),"虚拟商品发货处理", operateInfo.getProgramType()
							, operateInfo.getOperatorType(),operateInfo.getOperator());
					flag = true;
				}
			} catch (SQLException e) {
				log.error(e.getMessage(),e);
			}

			if(flag){
				//网商平台通知，已发货
				UpdateGoodsOrderStateRequest apiReq = new UpdateGoodsOrderStateRequest();
				apiReq.getBody().setTradeNo(businessOrder.getTradeNo());
				apiReq.getBody().setState(GoodsOrderEnum.State.WaitReceive.index());
				apiReq.getBody().setDeliverGoodsDate(deliverGoodsDate);
				apiReq.getBody().setDeliverGoodsNote(deliverGoodsNote);

				DefaultAPIResponse apiResp = CloudGoodsOrderAPIService.self().updateGoodsOrderState(apiReq);
				if(apiResp == null){
					log.error("{{0}}订单通知云平台已发货失败，无响应",businessOrder.getTradeNo());
				}else if(!DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())){
					log.error("{{0}}订单通知云平台已发货失败，响应：{{1}}",businessOrder.getTradeNo(),apiResp.getMsg());
				}
				return true;
			}
		}
		return false;
	}

	/**
	 * 收货处理
	 * @param tradeNo
	 * @return
	 */
	public boolean receiveGoods(String tradeNo,Integer receiveGoodsType,Date receiveGoodsDate) throws LogicException {
		if(StringTools.isNotBlank(tradeNo) && receiveGoodsType != null && receiveGoodsDate != null){
			SupplierBusinessOrder businessOrder = getByTradeNo(tradeNo);
			if(businessOrder == null){
				throw new LogicException("未找到订单信息");
			}

			if(!GoodsOrderEnum.State.WaitReceive.index().equals(businessOrder.getState())){
				throw new LogicException("订单状态必须是等待收货");
			}

			if(businessOrder.getDeliverGoodsDate() != null && businessOrder.getDeliverGoodsDate().after(receiveGoodsDate)){
				throw new LogicException("收货时间必须小于发货时间");
			}
			Conditions conditions = new Conditions(SupplierBusinessOrder.class);
			conditions.and().is("tradeNo",tradeNo);
			conditions.and().is("state", GoodsOrderEnum.State.WaitReceive.index());

			SupplierBusinessOrder updateEntity = new SupplierBusinessOrder();
			updateEntity.setReceiveGoodsType(EReceiveGoodsType.ManagerConfirm.index());
			updateEntity.setReceiveGoodsDate(receiveGoodsDate);
			updateEntity.setState(GoodsOrderEnum.State.WaitEvaluate.index());

			try {
				if(dao.updateNotNull(updateEntity,conditions) > 0) {
					return true;
				}
			} catch (SQLException e) {
				log.error(e.getMessage(),e);
			}
		}
		return false;
	}

	public boolean receiveGoods(String tradeNo, Integer receiveGoodsType, Date receiveGoodsDate, OperateInfo operateInfo) throws LogicException {
		if(StringTools.isNotBlank(tradeNo) && receiveGoodsType != null && receiveGoodsDate != null){
			SupplierBusinessOrder businessOrder = getByTradeNo(tradeNo);
			if(businessOrder == null){
				throw new LogicException("未找到订单信息");
			}

			if(!GoodsOrderEnum.State.WaitReceive.index().equals(businessOrder.getState())){
				throw new LogicException("订单状态必须是等待收货");
			}

			if(businessOrder.getDeliverGoodsDate() != null && businessOrder.getDeliverGoodsDate().after(receiveGoodsDate)){
				throw new LogicException("收货时间必须小于发货时间");
			}

			//TODO 网商平台通知，催收货
			/*
			ProjectAPIService apiService = ProjectAPIServiceFactory.getProjectAPIService(businessOrder.getProjectId());
			if(apiService != null) {
				ApplyReceiveGoodsRequest apiReq = new ApplyReceiveGoodsRequest();
				apiReq.getBody().setTradeNo(businessOrder.getTradeNo());
				apiReq.getBody().setReceiveGoodsDate(receiveGoodsDate);
				apiReq.getBody().setReceiveGoodsType(receiveGoodsType);

				ApplyReceiveGoodsResponse apiResp = apiService.applyReceiveGoods(apiReq);
				if(apiResp != null){
					if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
						if (GoodsOrderEnum.State.WaitEvaluate.index().equals(apiResp.getBody().getState())
								|| GoodsOrderEnum.State.Finish.index().equals(apiResp.getBody().getState())) {
							//等待评价或完成
							Conditions conditions = new Conditions(BusinessOrder.class);
							conditions.and().is("tradeNo", tradeNo);
							conditions.and().is("state", GoodsOrderEnum.State.WaitReceive.index());

							BusinessOrder updateEntity = new BusinessOrder();
							updateEntity.setReceiveGoodsType(apiResp.getBody().getReceiveGoodsType());
							updateEntity.setReceiveGoodsDate(apiResp.getBody().getReceiveGoodsDate());
							updateEntity.setState(apiResp.getBody().getState());
							try {
								if (dao.updateNotNull(updateEntity, conditions) > 0) {
									BusinessOrderLogService.self().addSuccess(tradeNo,"订单确认收货", operateInfo.getProgramType()
											,operateInfo.getOperatorType(),operateInfo.getOperator());
									return true;
								}
							} catch (SQLException e) {
								log.error(e.getMessage(), e);
							}
						} else if (GoodsOrderEnum.State.ReturnGoods.index().equals(apiResp.getBody().getState())) {
							Conditions conditions = new Conditions(BusinessOrder.class);
							conditions.and().is("tradeNo", tradeNo);
							conditions.and().is("state", GoodsOrderEnum.State.WaitReceive.index());

							BusinessOrder updateEntity = new BusinessOrder();
							updateEntity.setReceiveGoodsType(apiResp.getBody().getReceiveGoodsType());
							updateEntity.setReceiveGoodsDate(apiResp.getBody().getReceiveGoodsDate());
							updateEntity.setState(apiResp.getBody().getState());
							try {
								dao.updateNotNull(updateEntity, conditions);
							} catch (SQLException e) {
								log.error(e.getMessage(), e);
							}
							throw new LogicException("订单处于退货中");
						} else if (GoodsOrderEnum.State.Close.index().equals(apiResp.getBody().getState())) {
							throw new LogicException("订单已关闭");
						} else {
							log.error("{{0}}订单向销售渠道申请收货，返回状态不正确，信息：{{1:json}}", tradeNo, apiResp);
						}
					}else if(StringTools.isNotBlank(apiResp.getMsg())){
						throw new LogicException(apiResp.getMsg());
					}
				}else{
					log.error("{{0}}订单向销售渠道申请收货，响应失败，信息：{{1:json}}",tradeNo,apiResp);
				}
			}
			*/
		}
		return false;
	}

	/**
	 * 评价商品处理
	 * @return
	 */
	public boolean evaluateGoods(Supplier supplier,SupplierBusinessOrder businessOrder,OperateInfo operateInfo) throws LogicException {
		Conditions conditions = new Conditions(SupplierBusinessOrder.class);
		conditions.and().is("tradeNo", businessOrder.getTradeNo());
		conditions.and().is("state", GoodsOrderEnum.State.WaitEvaluate.index());

		SupplierBusinessOrder updateEntity = new SupplierBusinessOrder();
		updateEntity.setState(GoodsOrderEnum.State.Finish.index());

		boolean flag = false;
		try {
			if (dao.updateNotNull(updateEntity, conditions) > 0) {
				SupplierBusinessOrderLogService.self().addSuccess(businessOrder.getTradeNo(), operateInfo.getOperateNote(), operateInfo.getProgramType()
						, operateInfo.getOperatorType(), operateInfo.getOperator());
				flag = true;
			}
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}

		if (flag) {
			if (supplier.getAccountId() != null && StringTools.isNotBlank(supplier.getPayToken())) {
				//触发结算
				CloudPayAccountSettlementRequest apiReq = new CloudPayAccountSettlementRequest();
				apiReq.getBody().setAccountId(supplier.getAccountId());
				apiReq.getBody().setAccountToken(supplier.getPayToken());
				apiReq.getBody().setTradeNo(businessOrder.getPayTradeNo());
				apiReq.getBody().setBusinessTradeNo(businessOrder.getTradeNo());
				apiReq.getBody().setPayMoney(businessOrder.getPayMoney());
				apiReq.getBody().setSettlementType(CloudPayAccountEnum.SettlementType.PayeeRequest.index());
				apiReq.getBody().setNote("收款方请求" + businessOrder.getTradeNo() + "订单手动结算");

				CloudPayAccountSettlementResponse apiResp = CloudPayAccountAPIService.self().settlement(apiReq);
				if (apiResp != null) {
					log.info("触发云账号结算响应：{{0:json}}", apiResp);
				} else {
					log.error("触发云账号结算未响应");
				}
			}
			return true;
		}
		return false;
	}

	private String createTradeNo(Long supplierId) {
		String tradeNo = supplierId + IDTools.getTimestampID();

		Conditions condition = new Conditions(SupplierBusinessOrder.class);
		condition.and().is("tradeNo", tradeNo);
		try {
			if (dao.count(condition) > 0) {
				tradeNo = supplierId + IDTools.getTimestampNanoID();
				return tradeNo;
			} else {
				return tradeNo;
			}
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}
}
